﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using fanfu.Common;
using System.Data;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Configuration;

/// <summary>
///基类BasePage
/// </summary>
public class BasePage : Page
{
    //设置后台每页显示记录数
    protected int __AdminPageSize = 10;
    //设置前台每页显示记录数
    protected int __PageSize = 10;

	public BasePage()
    {
        //构造函数
	}

    #region 验证登陆状态
    /// <summary>
    /// 页面加载前验证登陆状态
    /// </summary>
    protected void Page_Init()
    {
        #region 301重定向
        if (HttpContext.Current.Request.Url.ToString().IndexOf("http://fanfublog.com") != -1)
        {
            Response.Clear();
            Response.StatusCode = 301;
            Response.Status = "301 MovedPermanently";
            if (HttpContext.Current.Request.Url.ToString().IndexOf("http://fanfublog.com") >= 0)
                Response.AddHeader("Location","http://www.fanfublog.com");
            Response.End();
        }
        #endregion

        #region 区域或IP封杀
        string _404html = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"><HTML><HEAD><TITLE>无法找到该页</TITLE><META HTTP-EQUIV=\"Content-Type\" Content=\"text/html; charset=GB2312\"><STYLE type=\"text/css\">   BODY { font: 9pt/12pt 宋体 }  H1 { font: 12pt/15pt 宋体 }  H2 { font: 9pt/12pt 宋体 }  A:link { color: red }  A:visited { color: maroon }</STYLE></HEAD><BODY><TABLE width=500 border=0 cellspacing=10><TR><TD> <h1>无法找到该页<font size='1' color='white'>lock</font></h1>您正在搜索的页面可能已经删除、更名或暂时不可用。<hr><p>请尝试以下操作：</p><ul><li>确保浏览器的地址栏中显示的网站地址的拼写和格式正确无误。</li><li>如果通过单击链接而到达了该网页，请与网站管理员联系，通知他们该链接的格式不正确。</li><li>单击<a href=\"javascript:history.back(1)\">后退</a>按钮尝试另一个链接。</li></ul><h2>HTTP 错误 404 - 文件或目录未找到。<br>Internet 信息服务 (IIS)</h2><hr><p>技术信息（为技术支持人员提供）</p><ul><li>转到 <a href=\"http://go.microsoft.com/fwlink/?linkid=8180\">Microsoft 产品支持服务</a>并搜索包括&ldquo;HTTP&rdquo;和&ldquo;404&rdquo;的标题。</li><li>打开&ldquo;IIS 帮助&rdquo;（可在 IIS 管理器 (inetmgr) 中访问），然后搜索标题为&ldquo;网站设置&rdquo;、&ldquo;常规管理任务&rdquo;和&ldquo;关于自定义错误消息&rdquo;的主题。</li></ul></TD></TR></TABLE></BODY></HTML>";
        string userIP = Request.UserHostAddress;
        IPLocation ipLocation = new QQWryLocator().Query(userIP);
        if (!string.IsNullOrEmpty(ipLocation.Country))
        {
            string sqlString = string.Format("SELECT COUNT(*) FROM BrowseLimit WHERE AreaorIP like '%{0}%' OR AreaorIP like '%{1}%'", userIP, ipLocation.Country);
            int result = int.Parse(SqlHelper.GetScalar(sqlString).ToString());
            if (result >= 1)
            {
                Response.Clear();
                Response.Write(_404html);
                Response.End();
                return;
            }
        }
        #endregion

        if (Request.Path.IndexOf("/admin") != -1)
        {
            if (CookieHelper.GetCookie("loginState") == string.Empty)
                Response.Redirect("Login.aspx");
        }
    }
    #endregion

    #region 注册客户端JS
    /// <summary>
    /// 客户端弹框
    /// </summary>
    /// <param name="msg">提示的内容</param>
    protected void Alert(string message)
    {
        ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "alert('" + message + "');", true);
    }

    /// <summary>
    /// 客户端运行JS
    /// </summary>
    /// <param name="js">待执行的JS</param>
    /// <param name="load">true页面加载后执行,false页面加载前执行</param>
    protected void RunJavascript(string javascript, bool load)
    {
        if (load == true)
            ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), javascript, true);
        else
            ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), javascript, true);
    }
    #endregion

    #region 动态加载JavaScript和Css
    /// <summary>
    /// 后台加载Css文件
    /// </summary>
    /// <param name="cssFileName">样式表路径如:css/base.css</param>
    protected void LoadCss(string cssFileName)
    {
        HtmlLink cssHtmlLink = new HtmlLink();
        cssHtmlLink.Href = HttpContext.Current.Request.ApplicationPath + cssFileName;
        cssHtmlLink.Attributes.Add("rel", "stylesheet");
        cssHtmlLink.Attributes.Add("type", "text/css");
        this.Header.Controls.Add(cssHtmlLink);
    }

    /// <summary>
    /// 后台加载JavaScript文件
    /// </summary>
    /// <param name="jsFileName">脚本路径如:js/app.js</param>
    protected void LoadJavaScript(string jsFileName)
    {
        HtmlGenericControl jsControl = new HtmlGenericControl();
        jsControl.TagName = "script";
        jsControl.Attributes.Add("src", HttpContext.Current.Request.ApplicationPath + jsFileName);
        jsControl.Attributes.Add("language", "javascript");
        jsControl.Attributes.Add("type", "text/javascript");
        jsControl.Attributes.Add("charset", "utf-8");
        this.Header.Controls.Add(jsControl);
    }
    #endregion

    #region 创建并保存缩略图
    /// <summary>
    /// 创建并保存缩略图
    /// </summary>
    /// <param name="FileDirectory">原图的上传目录</param>
    /// <param name="filename">原图文件名</param>
    /// <param name="maxWidth">缩略图宽度</param>
    /// <param name="maxHeight">缩略图高度</param>
    /// <returns>缩略图生成后的相对路径</returns>
    protected string CreateSmallImage(string FileDirectory, string filename, int maxWidth, int maxHeight)
    {
        System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(FileDirectory + filename));
        System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;

        Size newSize = NewSize(maxWidth, maxHeight, img.Width, img.Height);
        Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
        Graphics g = Graphics.FromImage(outBmp);

        //设置画布的描绘质量
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height),
            0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
        g.Dispose();

        //以下代码为保存图片时，设置压缩质量
        System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
        long[] quality = new long[1];
        quality[0] = 100;

        EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
        encoderParams.Param[0] = encoderParam;

        //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
        ImageCodecInfo jpegICI = null;
        for (int x = 0; x < arrayICI.Length; x++)
        {
            if (arrayICI[x].FormatDescription.Equals("JPEG"))
            {
                jpegICI = arrayICI[x];//设置JPEG编码
                break;
            }
        }
        if (jpegICI != null)
        {
            outBmp.Save(Server.MapPath(FileDirectory) + "small_" + filename, jpegICI, encoderParams);
        }
        else
        {
            outBmp.Save(Server.MapPath(FileDirectory) + "small_" + filename, thisFormat);
        }
        img.Dispose();
        outBmp.Dispose();
        return FileDirectory + "small_" + filename;
    }

    /// <summary>
    /// 计算新图片大小
    /// </summary>
    /// <param name="maxWidth">最大宽度</param>
    /// <param name="maxHeight">最大高度</param>
    /// <param name="width">宽度</param>
    /// <param name="height">高度</param>
    /// <returns></returns>
    protected Size NewSize(int maxWidth, int maxHeight, int width, int height)
    {
        double w = 0.0;
        double h = 0.0;
        double sw = Convert.ToDouble(width);
        double sh = Convert.ToDouble(height);
        double mw = Convert.ToDouble(maxWidth);
        double mh = Convert.ToDouble(maxHeight);

        if (sw < mw && sh < mh)
        {
            w = sw;
            h = sh;
        }
        else if ((sw / sh) > (mw / mh))
        {
            w = maxWidth;
            h = (w * sh) / sw;
        }
        else
        {
            h = maxHeight;
            w = (h * sw) / sh;
        }

        return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
    }
    #endregion

    #region 创建前台分页HTML
    /// <summary>
    /// 创建前台分页HTML
    /// </summary>
    /// <param name="rowsCount">记录总数</param>
    /// <param name="current">当前页码,从1开始</param>
    /// <param name="urlPage">当前页面名称</param>
    /// <returns>返回分页HTML</returns>
    public string CreatePaging(int rowsCount, int current, string urlPage)
    {
        string outstr = string.Empty;

        if (rowsCount <= __PageSize)
            return string.Empty;

        //页数计算,页数从1开始
        double dbPageCount = rowsCount / __PageSize;
        int pageCount = (int)dbPageCount;
        if (rowsCount % __PageSize != 0)
            pageCount += 1;

        if (current != 1)
            outstr += string.Format("<a href=\"{0}&page={1}\">上一页</a>", urlPage, current - 1);

        for (int i = 1; i <= pageCount; i++)
        {
            if (i == 2 && current - 5 > 1)
            {
                outstr += "<span>...</span>";
                i = current - 5;
            }
            else if (i == current + 5 && current + 5 < pageCount)
            {
                outstr += "<span>...</span>";
                i = pageCount - 1;
            }
            else
            {
                if (current == i)
                {
                    outstr += string.Format("<a class='current' href=\"javascript:;\">{0}</a>",i);
                }
                else
                {
                    outstr += string.Format("<a href=\"{0}&page={1}\">{2}</a>", urlPage, i, i);
                }
            }
        }

        if (current != pageCount)
            outstr += string.Format("<a href=\"{0}&page={1}\">下一页</a>", urlPage, current + 1);

        return outstr;
    }
    #endregion

    #region 创建后台分页HTML
    /// <summary>
    /// 创建后台分页HTML
    /// </summary>
    /// <param name="rowsCount">记录总数</param>
    /// <param name="current">当前页码,从1开始</param>
    /// <returns>返回分页HTML</returns>
    public string CreateAdminPaging(int rowsCount, int current)
    {
        if (rowsCount <= 0)
            return string.Empty;

        //页数计算,页数从1开始
        double dbPageCount = rowsCount / __AdminPageSize;
        int pageCount = (int)dbPageCount;
        if (rowsCount % __AdminPageSize != 0)
            pageCount += 1;

        //计算当前请求页属于第几组,10页为一组,组数从0开始
        double dbPageGroup = current / 10;
        int pageGroup = (int)dbPageGroup;
        if (current % 10 == 0)
            pageGroup -= 1;

        //计算循环次数
        int cycleNum = 0;
        if (pageCount >= (pageGroup + 1) * 10)
            cycleNum = pageGroup * 10 + 10;
        else
            cycleNum = pageCount;

        StringBuilder pagingHtml = new StringBuilder();
        pagingHtml.AppendFormat("<span class=\"count\">共&nbsp;{0}&nbsp;条数据&nbsp;共&nbsp;{1}&nbsp;页</span>", rowsCount, pageCount);

        //第一页
        if (current == 1)
        {
            pagingHtml.AppendFormat("<span>第一页</span>");
            pagingHtml.AppendFormat("<span>上一页</span>");
        }
        else
        {
            pagingHtml.AppendFormat("<a href=\"javascript:__doPostBack('pagecut','{0}');\">第一页</a>", 1);
            pagingHtml.AppendFormat("<a href=\"javascript:__doPostBack('pagecut','{0}');\">上一页</a>", current - 1);
        }

        //循环当前组内的页码
        for (int i = (pageGroup * 10) + 1; i <= cycleNum; i++)
        {
            if (i == current)
                pagingHtml.AppendFormat("<a class='number current' href=\"javascript:__doPostBack('pagecut','{0}');\">{1}</a>", i, i);
            else
                pagingHtml.AppendFormat("<a class='number' href=\"javascript:__doPostBack('pagecut','{0}');\">{1}</a>", i, i);
        }

        //最后一页
        if (current == pageCount)
        {
            pagingHtml.AppendFormat("<span>下一页</span>");
            pagingHtml.AppendFormat("<span>最后一页</span>");
        }
        else
        {
            pagingHtml.AppendFormat("<a href=\"javascript:__doPostBack('pagecut','{0}');\">下一页</a>", current + 1);
            pagingHtml.AppendFormat("<a href=\"javascript:__doPostBack('pagecut','{0}');\">最后一页</a>", pageCount);
        }
        return pagingHtml.ToString();
    }
    #endregion
}